package org.lboot.flow.model;

import cn.hutool.json.JSONUtil;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.Data;
import lombok.SneakyThrows;
import org.lboot.flow.constant.FlowNodeTypeConst;
import org.lboot.flow.model.node.*;

import java.io.Serializable;
import java.util.List;

/**
 * 流程模型
 * @author kindear
 *
 */
@Data
public class FlowModel implements Serializable {

    @SneakyThrows
    public static BaseModel getNodeModel(List<BaseModel> nodeList, String nodeId) {

        if(null == nodeList || nodeList.isEmpty()) {
            return null;
        }
        ObjectMapper objectMapper = new ObjectMapper();
        // JSON转化
        JsonNode root = objectMapper.readTree(JSONUtil.toJsonStr(nodeList));
        if (root.isArray()){
            for (JsonNode node:root){
                String id = node.get("id").asText();
                String type = node.get("nodeType").asText();
                if (id.equals(nodeId)){
                    if (type.equals(FlowNodeTypeConst.START_NODE)){
                        return JSONUtil.toBean(node.toString(), StartModel.class);
                    }
                    else if (type.equals(FlowNodeTypeConst.TASK_NODE)){
                        return JSONUtil.toBean(node.toString(), TaskModel.class);
                    }
                    else if (type.equals(FlowNodeTypeConst.DECISION_TASK_NODE)){
                        return JSONUtil.toBean(node.toString(), DecisionTaskModel.class);
                    }
                    else if (type.equals(FlowNodeTypeConst.AUTO_DECISION_TASK_NODE)){
                        return JSONUtil.toBean(node.toString(), AutoDecisionModel.class);
                    }
                    else if (type.equals(FlowNodeTypeConst.COMMAND_NODE)){
                        return JSONUtil.toBean(node.toString(), CommandModel.class);
                    }
                    else if (type.equals(FlowNodeTypeConst.END_NODE)){
                        return JSONUtil.toBean(node.toString(), EndModel.class);
                    }
                    else if (type.equals(FlowNodeTypeConst.SUB_FLOW_NODE)){
                        return JSONUtil.toBean(node.toString(), SubFlowModel.class);
                    }
                    else if (type.equals(FlowNodeTypeConst.TRIGGER_NODE)){
                        return JSONUtil.toBean(node.toString(), TriggerModel.class);
                    }
                    else if (type.equals(FlowNodeTypeConst.EXCLUSIVE_GATEWAY_NODE)){
                        return JSONUtil.toBean(node.toString(), ExclusiveGatewayModel.class);
                    }
                    else if (type.equals(FlowNodeTypeConst.PARALLEL_GATEWAY_NODE)){
                        return JSONUtil.toBean(node.toString(), ParallelGatewayModel.class);
                    }

                }
            }
        }
        return null;
    }

}

